package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;
    @Autowired
    private StudentMapper studentMapper;

    /**
     * 分页查询
     *
     * @param param     查询条件
     * @return 分页结果
     */

    @Override
    public PageResult<Clazz> getPageResult(ClazzQueryParam param) {
        Page<Clazz> page = Page.of(param.getPage(), param.getPageSize());

        //根据最后修改时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));

        //使用lambdaQuery方法构建查询条件
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Clazz::getName, param.getName())
                .between(param.getBegin() != null && param.getEnd() != null, Clazz::getEndDate, param.getBegin(), param.getEnd())
                .page(page);

        // 获取班级集合
        List<Clazz> clazzs = page.getRecords();

        // 获取所有班级的班主任id
        List<Long> masterIds = clazzs.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());

        //判断有没有班主任
        if (!masterIds.isEmpty()) {
            //提取出相关id的员工信息
            List<Emp> masters = empService.listByIds(masterIds);

            clazzs.forEach(clazz -> {
                masters.forEach(master -> {
                    if (clazz.getMasterId() != null && clazz.getMasterId().equals(master.getId())) {
                        clazz.setMasterName(master.getName());
                    }
                });
                if(LocalDate.now().isBefore(clazz.getBeginDate()) ){
                    clazz.setStatus("未开班");
                }else if (LocalDate.now().isAfter(clazz.getEndDate())){
                    clazz.setStatus("已结课");
                }else{
                    clazz.setStatus("在读");
                }
            });
        }

        // 封装结果并返回
        return new PageResult<>(page.getTotal(), clazzs);
    }


    /**
     * 新增班级
     * @param clazz 班级信息
     */
    @Override
    public void saveClazz(Clazz clazz) {
        //调用service层方法保存班级信息
        //补全基础属性
        clazz.setUpdateTime(LocalDateTime.now());

        save(clazz);

    }

    @Override
    public void deleteById(Integer id) {
        Long clazzId = Long.valueOf(id);
        Long count;
//从student中统计clazzId等于clazzId的记录数，使用Mybatis Plus的查询方法
        LambdaQueryWrapper<Student> studentLambdaQueryWrapper = new LambdaQueryWrapper<Student>()
                .eq(Student::getClazzId, clazzId);
        count = studentMapper.selectCount(studentLambdaQueryWrapper);
        if (count > 0) {
            throw new RuntimeException("该班级下存在学生，请先删除该班级下的学生");
        }
        this.removeById(id);
    }
}
